'use strict';

/**
 * Truncate Filter
 * @Param text
 * @Param length, default is 10
 * @Param end, default is "..."
 * @return string
 */
angular.module('filters', [])
	.filter('truncate', function () {
	    return function (text, length, end) {
	    	if(text == null)
	    		return ;

	        if (isNaN(length))
	            length = 10;
	
	        if (end === undefined)
	            end = "...";
	
	        if (text.length <= length) {
	            return text;
	        }
	        else {
	            return String(text).substring(0, length) + end;
	        }
	    };
	})

	.filter('regionFilter', function () {
	    return function (text, idPaysParent) {
    		var filteredArray = [];
    		angular.forEach(text, function(value, key){
    			if(value.idPays == idPaysParent || value.idPays == null)
    				filteredArray.push(value);				
			}, text, filteredArray, idPaysParent);
	        return filteredArray;
	    };
	})

	// filtre affichage taile en mode lisible
	.filter('sizeConverterFilter', function () {
	    return function (size, precision) {
	    	if (precision == 0 || precision == null){
				precision = 1;
			}
			if (size == 0 || size == null){
				return "";
			}
			else if( !isNaN(size) )
			{
				var sizes = ['Octet', 'Ko', 'Mo', 'Go', 'To'];
				var posttxt = 0;

				if (size < 1024) {
					return Number(size) + " " + sizes[posttxt];
				}

				while( size >= 1024 ) {
					posttxt++;
					size = size / 1024;
				}

				var power = Math.pow (10, precision);
				var poweredVal = Math.ceil (size * power);

				size = poweredVal / power;

				return size + " " + sizes[posttxt];
			}else{
				return "";
			}
	    };
	});